package com.bls.cate.ui.activity.write_article;

import android.app.Application;
import android.os.Environment;

import com.blankj.utilcode.util.LogUtils;
import com.lzy.imagepicker.bean.ImageItem;

import java.io.File;
import java.util.ArrayList;

import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

public class WriteArticleUtil {

    /**
     * 获取压缩后的图片
     */
    public static ArrayList<ImageItem> getLubanResult(final Application application, final ArrayList<ImageItem> pathList) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0, j = pathList.size(); i < j; i++) {
                    final int finalI = i;
                    if (!pathList.get(finalI).hasCompress)
                        Luban.with(application).setTargetDir(getLubanSavePath()).load(pathList.get(i).getPath()).setCompressListener(new OnCompressListener() {
                            @Override
                            public void onStart() {
                                LogUtils.i("Luban", "onStart");
                            }

                            @Override
                            public void onSuccess(File file) {
                                pathList.get(finalI).hasCompress = true;
                                pathList.get(finalI).setPath(file.getAbsolutePath());
                                LogUtils.i("Luban", "onSuccess");
                            }

                            @Override
                            public void onError(Throwable e) {
                                pathList.get(finalI).hasCompress = true;
                                LogUtils.i("Luban", e);
                            }
                        }).launch();
                }
            }
        }).start();
        System.out.println(pathList);
        return pathList;
    }

    /**
     * 获取鲁班压缩保存图片的地址
     *
     * @return 地址
     */
    private static String getLubanSavePath() {
        String path = Environment.getExternalStorageDirectory() + "/Cate/images/";
        File file = new File(path);
        if (file.mkdirs()) {
            return path;
        }
        return path;
    }
}
